package com.zz.zjc;

import com.zz.zjc.dao.UtilDao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import java.io.File;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
@WebAppConfiguration
public class MakeCodeUtil {

    Logger logger = LoggerFactory.getLogger(MakeCodeUtil.class);

    @Autowired
    UtilDao utilDao;
    /**
     * 创建一个带有 增删改查  add  delete update get  的mapper    和对应的dao
     */
    @Test
    public void make(){
        boolean isModel=true;
        String packageName="com.zz.zjc";
        String modleName="Verification";
        String tableNmae="verification";



        String daoPackage=packageName+".dao";
        String namespace=daoPackage+"."+modleName+"Dao";

        String daoFilePath="src/main/java/"+packageName.replace(".","/")+"/dao/";
        String modelFilePath="src/main/java/"+packageName.replace(".","/")+"/model/";
        String mapperFilePath="src/main/resources/mapper/";

        String daoClassName=modleName+"Dao";
        String daoName=daoClassName+".java";
        String mapperName=modleName+"DaoMapper.xml";

        String modelType=isModel?(packageName+".model."+modleName):"java.util.HashMap";
        modleName=isModel?modleName:"HashMap";

        String MapperFileNmae=mapperFilePath+mapperName;
        String daoFileName=daoFilePath+daoName;

        //加载表结构数据
        List<HashMap> columnsList=utilDao.getColumnsListByName(tableNmae);

        if (isModel){
            //makeModel(packageName,columnsList,modleName,modelFilePath+modleName+".java");
        }
        //makeDao(daoClassName,modelType,modleName,daoFileName);
        makeMapper(tableNmae,namespace ,modelType,MapperFileNmae,columnsList);

    }
    private void makeModel(String packageName, List<HashMap> columnsList,String className,String fileNmae){

        String Str="";
        for (int i = 0; i <columnsList.size(); i++) {
            HashMap<String,Object> col=columnsList.get(i);
            String name=col.get("Field")+"";
            Str+="    private String "+name+";\n" ;
        }
        String text="package "+packageName+".model;\n" +
                "\n" +
                "import java.io.Serializable;\n" +
                "\n" +
                "public class "+className+" implements Serializable {\n" +

                Str +
                "}\n";
        try{
            File file =new File(fileNmae);
            if(!file.exists()){
                file.createNewFile();
            }else {
               /* logger.info("当前model文件已存在,创建失败");
                return;*/
            }
            FileWriter fileWritter = new FileWriter(fileNmae);
            fileWritter.write(text);
            fileWritter.close();
            logger.info("model文件创建成功");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    private void makeDao(String daoClassName, String modelType,String modelTypeName,String fileNmae){

        String text="package com.zz.zjc.dao;\n" +
                "\n" +
                "import org.apache.ibatis.annotations.Param;\n" +
                "\n" +
                "import "+modelType+";\n" +
                "import java.util.List;\n" +
                "\n" +
                "public interface "+daoClassName+" extends BaseDao<"+modelTypeName+">{\n" +
                "\n" +
                "    List<"+modelTypeName+"> getList(@Param(\"startPage\") Integer page, @Param(\"pageSize\") Integer pageSize);\n" +
                "}\n";
        try{
            File file =new File(fileNmae);
            if(!file.exists()){
                file.createNewFile();
            }else {
                logger.info("当前Dao文件已存在,创建失败");
                return;
            }
            FileWriter fileWritter = new FileWriter(fileNmae);
            fileWritter.write(text);
            fileWritter.close();
            logger.info("dao文件创建成功");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    private void makeMapper(String tableNmae,String namespace,String modelType,String fileNmae,List<HashMap> columnsList){
        String keyId=null;

        String add0="";
        String add1="";
        String update0="";
        for (int i = 0; i <columnsList.size() ; i++) {
            HashMap<String,Object> col=columnsList.get(i);
            String name=col.get("Field")+"";
            boolean isKeyId=false;
            if(null!=col.get("Key")&&"PRI".equals(col.get("Key"))){
                keyId=name;
                isKeyId=true;
            }
            if(!isKeyId){
                add0+="\t\t\t<if test=\""+name+" != null\">"+name+",</if>\n";
                add1+="\t\t\t<if test=\""+name+" != null\">#{"+name+"},</if>\n";
                update0+="\t\t\t<if test=\""+name+" != null\">"+name+" = #{"+name+"},</if>\n";
            }
        }
        if(keyId==null){
            logger.info("没有主键，创建Mapper.xml文件失败");
            return;
        }


        String text="<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" +
                "<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\" >\n" +
                "<mapper namespace=\""+namespace+"\">\n" +
                "\n" +

                "\t<!-- 新增 -->\n" +
                "\t<insert id=\"add\" useGeneratedKeys=\"true\" keyProperty=\"id\" parameterType=\""+modelType+"\">\n" +
                "\t\tinsert into `"+tableNmae+"`\n" +
                "\t\t<trim prefix=\"(\" suffix=\")\" suffixOverrides=\",\">\n" +
                add0 +
                "\t\t</trim>\n" +
                "\t\t<trim prefix=\"values (\" suffix=\")\" suffixOverrides=\",\">\n" +
                add1 +
                "\t\t</trim>\n" +
                "\t</insert>\n" +


                "\n" +
                "\t<!-- 删除 -->\n" +
                "\t<delete id=\"delete\" >\n" +
                "\t\tdelete from `"+tableNmae+"`\n" +
                "\t\twhere "+keyId+" = #{id}\n" +
                "\t</delete>\n" +


                "\n" +
                "\t<!-- 修改 -->\n" +
                "\t<update id=\"update\" parameterType=\""+modelType+"\">\n" +
                "\t\tupdate "+tableNmae+"\n" +
                "\t\t<set>\n" +
                update0 +
                "\t\t</set>\n" +
                "\t\twhere "+keyId+" = #{"+keyId+"}\n" +
                "\t</update>\n" +
                "\n" +


                "\n" +
                "\t<!-- 查询 -->\n" +
                "\t<select id=\"get\" resultType=\""+modelType+"\" >\n" +
                "\t\tselect * from `"+tableNmae+"` WHERE "+keyId+"=#{"+keyId+"};\n" +
                "\t</select>\n" +


                "\n" +
                "\t<!-- 查询分页列表 -->\n" +
                "\t<select id=\"getList\" resultType=\""+modelType+"\" >\n" +
                "\t\tselect * from `"+tableNmae+"`  LIMIT #{startPage},#{pageSize};;\n" +
                "\t</select>\n" +

                "\n" +
                "</mapper>";

        try{
            File file =new File(fileNmae);
            if(!file.exists()){
                file.createNewFile();
            }else {
                logger.info("当前Mapper文件已存在,创建失败");
                return;
            }
            FileWriter fileWritter = new FileWriter(fileNmae);
            fileWritter.write(text);
            fileWritter.close();
            logger.info("mapper文件创建成功");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}


